package com.itfreer.print.base.itextpdf;

import java.io.IOException;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;

/**
 * 解决中文显示的问题
 */
public class ChineseFontsProvider extends XMLWorkerFontProvider {
	
	private static BaseFont defult;
	private static BaseFont st;
	private static BaseFont yh;
	
	public ChineseFontsProvider() {
		super(null, null);
	}
	
	/**
	 * 默认字体
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static BaseFont getDefultBaseFont() throws DocumentException, IOException{
		if(defult==null){
			defult = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		}
		return defult;
	}
	
	/**
	 * 宋体
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static BaseFont getSTBaseFont() throws DocumentException, IOException{
		if(st==null){
			st = BaseFont.createFont("/print/ttf/simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		}
		return st;
	}
	
	/**
	 * 仿宋体
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static BaseFont getFSBaseFont() throws DocumentException, IOException{
		if(st==null){
			st = BaseFont.createFont("/print/ttf/fangsong.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		}
		return st;
	}
	
	/**
	 * 微软雅黑
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static BaseFont getYHBaseFont() throws DocumentException, IOException{
		if(yh==null){
			yh = BaseFont.createFont("/print/ttf/yahei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		}
		return yh;
	}

	@Override
	public Font getFont(final String fontname, String encoding, float size, final int style) {
		try {
			if (fontname == null) {
				BaseFont baseFont = getDefultBaseFont();
				Font font = new Font(baseFont, size, style);
				return font;
			} else if (fontname.equals("宋体") || fontname.equals("SimSun")) {
				BaseFont baseFont = getSTBaseFont();
				Font font = new Font(baseFont, size, style);
				return font;
			} else if (fontname.equals("仿宋") || fontname.equals("FangSong")) {
				BaseFont baseFont = getFSBaseFont();
				Font font = new Font(baseFont, size, style);
				return font;
			} else if (fontname.equals("微软雅黑") || fontname.equals("Microsoft YaHei")) {
				BaseFont baseFont = getYHBaseFont();
				Font font = new Font(baseFont, size, style);
				return font;
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.getFont(fontname, encoding, size, style);
	}
}
